﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Collections;
using System.Linq.Expressions;
using System.Web.Security;
using AL.Common;
using AL.DAL;
using AL.DAL.Core;
using AL.DAL.Models;


namespace AL.BLL {

    /// <summary>
    /// HH: 用户角色 业务逻辑操作实现类
    /// </summary>
    public class UserService : ServiceBase<User>, IUserService {
        private readonly IUnitOfWork unitOfWork;
        private readonly IUserRepository userRepository;
        private readonly IRoleRepository roleRepository;
        //private readonly MembershipProvider _Provider;

        public UserService(IUnitOfWork unitOfWork, IUserRepository userRepository, IRoleRepository roleRepository) {
            //_Provider = provider ?? Membership.Provider;

            this.unitOfWork = unitOfWork;
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;

            // 注意：一定要注册这个对象，否则分页查询会无效
            _Repository = userRepository;
        }


        public int MinPasswordLength {
            get {
                return 6;
            }
        }


        #region 　< 查询操作 >

        public IEnumerable<User> GetUsers() {
            userRepository.ProxyCreationEnabled = false;
            var users = userRepository.GetAll();
            return users;
        }

        public User GetUser(string userName) {
            //userRepository.ProxyCreationEnabled = false;
            var user = userRepository.GetById(userName);
            return user;
        }

        public bool ValidateUser(string userName, string password) {
            userRepository.ProxyCreationEnabled = false;
            bool r = false;

            var user = GetUser(userName);
            if (user != null && user.UserName.Length > 0) {
                if (AL.Security.TripleDES.Decrypt(user.Password) == password) {
                    r = true;
                }
            }

            return r;
        }

        #endregion


        #region 　< 新增、修改、删除、保存 锁定操作 >

        // 提交保存操作
        public void Save() {
            unitOfWork.Commit();
        }

        // 创建用户
        public MembershipCreateStatus CreateUser(string userName, string password, string email) {
            User r = new User();
            r.UserName = userName;
            r.Password = password;
            r.UserEmail = email;

            return CreateUser(r);
        }
        // 创建用户
        public MembershipCreateStatus CreateUser(User user) {
            user.Password = AL.Security.TripleDES.Encrypt(user.Password);
            user.CreateDate = DateTime.Now;
            user.IsApproved = true;
            user.LoginTimes = 0;
            user.LastLoginIP = AL.Common.WebHelper.GetWebClientIP();
            user.LastLoginTime = DateTime.Now;
            user.LastPasswordChangeTime = DateTime.Now;
            user.LastActivityTime = DateTime.Now;


            if (user.UserNickName == null || user.UserNickName == "") {
                user.UserNickName = user.UserName;
            }
            userRepository.Create(user);
            Save();

            return MembershipCreateStatus.Success;
        }

        // 修改用户
        public bool UpdateUser(User user) {
            userRepository.Update(user);
            Save();

            return true;
        }

        // 删除用户
        public void DeleteUser(string userName) {
            if (userName.ToLower() != "havent") {
                var user = GetUser(userName);

                // 清除用户拥有的所有角色
                userRepository.ClearRole(userName);
                userRepository.Delete(user);

                Save();
            } else {
                throw new ArgumentException("超级管理员不允许删除！");
            }
        }


        // 锁定用户
        public bool LockUser(string userName) {
            return UserLockOrNot(userName, true);
        }
        // 解锁用户
        public bool UnLockUser(string userName) {
            return UserLockOrNot(userName, false);
        }
        private bool UserLockOrNot(string userName, bool isLocking) {
            bool r = false;
            var user = GetUser(userName);
            if (user != null && user.UserName.Length > 0) {
                user.IsApproved = isLocking;
                userRepository.Update(user);
                Save();
                r = true;
            }

            return r;
        }

        // 修改密码
        public bool ChangePassword(string userName, string oldPassword, string newPassword) {
            bool r = false;
            var user = GetUser(userName);
            if (user != null && user.UserName.Length > 0) {
                string oPwd = AL.Security.TripleDES.Encrypt(oldPassword);
                if (user.Password == oPwd) {
                    user.Password = AL.Security.TripleDES.Encrypt(newPassword);
                    userRepository.Update(user);
                    Save();
                    r = true;
                } else {
                    r = false;
                }

            }

            return r;
        }
        #endregion


        public IEnumerable SqlQueryForDynamic(string sql, params object[] parameters) {
            return userRepository.SqlQueryForDynamic(sql, parameters);
        }


        #region 　< Role 角色相关操作 >

        public void AssignRole(string userName, List<int> roleIDs) {
            userRepository.AssignRole(userName, roleIDs);
            Save();
        }


        public void ClearRole(string userName) {
            userRepository.ClearRole(userName);
            Save();
        }


        public void CreateRole(Role role) {
            roleRepository.Create(role);
            Save();
        }
        public void UpdateRole(Role role) {
            roleRepository.Update(role);
            Save();
        }
        public void DeleteRole(int roleID) {
            var role = GetRole(roleID);
            roleRepository.Delete(role);
            Save();
        }


        public Role GetRole(int roleID) {
            var role = roleRepository.GetById(roleID);
            return role;
        }
        public IEnumerable<Role> GetRoles() {
            var roles = roleRepository.GetAll();
            return roles;
        }

        #endregion


    }






    /// <summary>
    /// HH: 用户角色 业务逻辑操作 接口类
    /// </summary>
    public interface IUserService : IServiceBase<User> {
        /// <summary>
        /// 最短密码长度
        /// </summary>
        int MinPasswordLength { get; }

        #region 　< 查询操作 >

        /// <summary>
        /// HH: 获取所有用户集合
        /// </summary>
        IEnumerable<User> GetUsers();
        /// <summary>
        /// HH: 根据用户名获取一个用户对象
        /// </summary>
        User GetUser(string userName);

        /// <summary>
        /// HH: 用户登录验证
        /// </summary>
        bool ValidateUser(string userName, string password);

        #endregion

        #region 　< 新增、修改、删除、保存 锁定操作 >

        /// <summary>
        /// HH: 新建用户（同时新增相关表记录）
        /// </summary>
        MembershipCreateStatus CreateUser(User user);
        /// <summary>
        /// HH: 新建用户（同时新增相关表记录）
        /// </summary>
        MembershipCreateStatus CreateUser(string userName, string password, string email);

        /// <summary>
        /// HH: 修改用户
        /// </summary>
        bool UpdateUser(User user);
        /// <summary>
        /// HH: 删除用户（级联删除）
        /// </summary>
        void DeleteUser(string userName);

        /// <summary>
        /// HH: 锁定用户（IsApproved = false）
        /// </summary>
        bool LockUser(string userName);

        /// <summary>
        /// HH: 解锁用户（IsApproved = true）
        /// </summary>
        bool UnLockUser(string userName);

        /// <summary>
        /// HH: 修改用户密码
        /// </summary>
        bool ChangePassword(string userName, string oldPassword, string newPassword);

        /// <summary>
        /// HH: 保存操作
        /// </summary>
        void Save();

        #endregion


        /// <summary>
        /// HH: 直接输入 SQL 语句或者存储过程 动态创建类并返回实例
        /// </summary>
        IEnumerable SqlQueryForDynamic(string sql, params object[] parameters);



        #region 　< Role 角色相关操作 >

        /// <summary>
        /// HH: 重新设置用户对应的所有角色集合
        /// </summary>
        void AssignRole(string userName, List<int> roleIDs);

        /// <summary>
        /// HH: 清空用户的角色绑定
        /// </summary>
        /// <param name="userName"></param>
        void ClearRole(string userName);

        ///// <summary>
        ///// HH: 创建角色
        ///// </summary>
        //void CreateRole(Role role);
        ///// <summary>
        ///// HH: 修改角色
        ///// </summary>
        //void UpdateRole(Role role);
        ///// <summary>
        ///// HH: 根据角色ID删除一个角色
        ///// </summary>
        //void DeleteRole(int roleID);

        ///// <summary>
        ///// HH: 根据角色ID获取一个角色对象
        ///// </summary>
        //Role GetRole(int roleID);
        ///// <summary>
        ///// HH: 获取所有角色集合
        ///// </summary>
        //IEnumerable<Role> GetRoles();

        #endregion




    }

}